#!/usr/bin/env python
"""Run coverstore server.

Usage:

start coverstore using dev webserver:

    ./scripts/coverstore-server coverstore.yml 8080

start coverstore as fastcgi:

    ./scripts/coverstore-server coverstore.yml fastcgi 7070

start coverstore using gunicorn webserver:

    ./scripts/coverstore-server coverstore.yml --gunicorn -b 0.0.0.0:8080

"""

import os
import sys

import _init_path  # noqa: F401  Imported for its side effect of setting PYTHONPATH
import web

web.config.debug = False


def setup_env():
    # make sure PYTHON_EGG_CACHE is writable
    os.environ['PYTHON_EGG_CACHE'] = "/tmp/.python-eggs"

    # required when run as fastcgi
    os.environ['REAL_SCRIPT_NAME'] = ""


def start_server():
    from openlibrary.coverstore import server

    server.main(*sys.argv[1:])


def start_gunicorn_server():
    """Starts the coverstore server using gunicorn server."""
    from gunicorn.app.base import Application

    configfile = sys.argv.pop(1)

    class WSGIServer(Application):
        def init(self, parser, opts, args):
            pass

        def load(self):
            from openlibrary.coverstore import code, server

            server.setup(configfile)
            return code.app.wsgifunc(https_middleware)

    WSGIServer("%prog coverstore.yml --gunicorn [options]").run()


def https_middleware(app):
    """Hack to support https even when the app server http only.

    The nginx configuration has changed to add the following setting:

        proxy_set_header X-Scheme $scheme;

    Using that value to overwrite wsgi.url_scheme in the WSGI environ,
    which is used by all redirects and other utilities.
    """
    print("** https_middleware")

    def wrapper(environ, start_response):
        print("HTTP_X_SCHEME", environ.get("HTTP_X_SCHEME"))
        if environ.get('HTTP_X_SCHEME') == 'https':
            environ['wsgi.url_scheme'] = 'https'
        return app(environ, start_response)

    return wrapper


if __name__ == "__main__":
    setup_env()
    if "--gunicorn" in sys.argv:
        sys.argv.pop(sys.argv.index("--gunicorn"))
        start_gunicorn_server()
    else:
        start_server()
